package com.bytedance.video.common;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

public class JwtUtil {

    //设置token为一天
    private static long time = 1000 * 60 * 60 * 20;

    private static final String admin = "xiaoyu";

    private JwtUtil() {
    }

    public static String createToken(Long userid) {

        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("typ", "JWT");
        objectObjectHashMap.put("alg", "HS256");
        String token = Jwts
                .builder()
                .setHeaderParams(objectObjectHashMap)
                .claim("userid", userid)
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, admin)
                .compact();
        return token;
    }

    public static Boolean checkToken(String token) {
        return Jwts.parser().isSigned(token);
    }

    public static Long parseToken(String token) {
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(admin).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        Integer userid = (Integer) body.get("userid");
        return Long.parseLong(userid.toString());
    }

}
